const https = require('https')
const cheerio = require('cheerio')
const fs = require('fs')

https.get('https://movie.douban.com/top250',function(res) {
    console.log(res);
    let html =''
    res.on('data',function(chuck) { // 监听获取数据的事件
        html += chuck
    })
    res.on('end',function() { // 从改地址获取事件结束
        // console.log(html);
        const $ = cheerio.load(html);

        let allFilms = []
        $('li .item').each(function() {
      const title = $('.info .hd .title', this).text()
      const star = $('.rating_num',this).text()
      const pic = $('.pic img',this).attr('src')
      allFilms.push({title,star,pic})
        })
        console.log(allFilms);
        fs.writeFile('./file.json',JSON.stringify(allFilms), function(err) {
            if(!err) {
                console.log('文件写入成功');
            }
        })
    }) 
})